/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.servlets;

import com.jmooc.entity.Course;
import com.jmooc.entity.CourseModule;
import com.jmooc.entity.ReadCourse;
import com.jmooc.entity.User;
import com.jmooc.service.CourseModuleService;
import com.jmooc.service.ReadCourseService;
import com.jmooc.service.UserService;
import java.io.IOException;
import java.util.Date;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Group
 */
@WebServlet(name = "CourseModuleServlet", urlPatterns = {"/module/*"} )
public class CourseModuleServlet extends HttpServlet {

    @EJB
    private CourseModuleService courseModuleService;
    
    @EJB
    private ReadCourseService readCourseService;
    
    @EJB
    private UserService userService;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Long courseModuleId = Long.valueOf(request.getPathInfo().substring(1));
        
        CourseModule courseModule = null;
        
        try {
            courseModule = courseModuleService.getById(courseModuleId);
            
            request.setAttribute("module", courseModule);
            
            User user = userService.getById((Long)session.getAttribute("userId"));
            
            Course course = courseModule.getCourse();
            
            // Si c'est là première fois qu'une personne suit le cours, on l'enregistre dans ses cours
            if (!readCourseService.isUserAlreadyReadingACourse(user, course)) {
                ReadCourse rc = new ReadCourse();
                rc.setCourse(course);
                rc.setUser(user);
                rc.setReadingDate(new Date());
                readCourseService.create(rc);
            }
        } catch (Exception e) {
            request.setAttribute("message", "Ce cours n'existe pas ou plus");
        }
        
        request.getRequestDispatcher("/jsp/module.jsp").forward(request, response);
    }

}
